﻿using DevExpress.CodeParser.VB.Preprocessor;
using DevExpress.DataAccess.Native.Data;
using DevExpress.Mvvm.Native;
using DevExpress.Office.Crypto;
using DevExpress.Xpo.DB.Helpers;
using DevExpress.XtraEditors;
using FuelDXApplication1;
using FuelDXApplication1.Entity;
using FuelDXApplication1.MksWinform;
using MySqlConnector;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Xpo.Helpers.AssociatedCollectionCriteriaHelper;
using static FuelDXApplication1.MksWinform.FuelAdd;

namespace FuelDXApplication1.HqhWinform
{
    public partial class ToBeEscalated : DevExpress.XtraEditors.XtraForm
    {

        private int pageIndex = 1;
        private int pageSize = 2;
        int pageCount;
        int TotalCount;

        public int Value { get; set; }
        private object receivedData;
        public ToBeEscalated()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 待上报列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ToBeEscalated_Load(object sender, EventArgs e)
        {
            GetToBeEscalated();
            await GetFuelType();
        }

        public async void GetToBeEscalated()
        {
            PageGetBase pagegetbase = new(pageIndex, pageSize);

            var list = DBHelper.Query<BasicInformation>();
            // gridControl1.DataSource = list.Result;
            TotalCount = list.Result.Count();
            pageCount = (int)Math.Ceiling(TotalCount * 1.0 / pagegetbase.pageSize);
            var pageinfo = list.Result.OrderBy(x => x.FuelParameter).Skip((pagegetbase.pageIndex - 1) * pagegetbase.pageSize).Take(pagegetbase.pageSize);
            gridControl1.DataSource = pageinfo;
        }


        /// <summary>
        /// /上报
        /// </summary>
        /// <returns></returns>
        private async Task UpdateStatus()
        {
            // 获取选中的行索引
            int[] rownumber = this.gridView1.GetSelectedRows();

            if (rownumber.Length > 0)
            {
                // 遍历选中的行索引
                foreach (int rowIndex in rownumber)
                {
                    if (rowIndex >= 0)  // 确保行索引有效
                    {
                        // 获取当前行的 BasicInformation 数据项
                        var item = this.gridView1.GetRow(rowIndex) as BasicInformation;

                        if (item == null)
                        {
                            MessageBox.Show("未查询到数据");
                            return;
                        }

                        // 判断节假日
                        var str = DBHelper.Query<Holiday>();
                        var holiday = str.Result.AsQueryable();
                        bool isHoliday = false;

                        foreach (var it in holiday)
                        {
                            if (item.DateOfImport >= it.StartDate && item.DateOfImport <= it.EndDate)
                            {
                                isHoliday = true;
                                break; // 找到节假日后跳出循环
                            }
                        }

                        if (isHoliday)
                        {
                            MessageBox.Show("当前是节假日，请稍后重试");
                            return;
                        }

                        // 获取当前的日期时间
                        DateTime timestr = DateTime.Now;
                        // 计算当前时间和 item.DateOfImport 之间的时间差
                        TimeSpan timeDifference = timestr - item.DateOfImport;
                        // 比较日期，不考虑时间部分
                        if (timeDifference.TotalHours < 48)
                        {
                            var res = await HttpClientHelper.RequestUrl<BasicInformation, ApiResult<string>>(
                                "https://localhost:44341/",
                                "api/app/fuel-synchronization/basic-inform",
                                MethodType.Post,
                                item);

                            if (res.Code == 200)
                            {
                                FeedbackCode feedbackCode = new FeedbackCode(item.ICPRecordNumber, item.FeedbackCode);
                                feedbackCode.Show();
                                return;
                            }
                        }
                        else
                        {
                            // 日期相等
                            Console.WriteLine("日期不相等");
                            SupplementaryTransmission supplementaryTransmission = new SupplementaryTransmission();
                            supplementaryTransmission.Show();
                            return;
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择一行数据");
            }

        }

        /// <summary>
        /// /批量上报
        /// </summary>
        private async Task AllUpdateStatus()
        {
            int[] rownumber = this.gridView1.GetSelectedRows();

            if (rownumber.Length > 0)
            {
                // 收集所有选中的项
                var itemsToUpload = new List<BasicInformation>();
                foreach (int rowIndex in rownumber)
                {
                    var item = this.gridView1.GetRow(rowIndex) as BasicInformation;
                    if (item != null)
                    {
                        itemsToUpload.Add(item);
                    }
                }

                // 判断节假日
                var holiday = DBHelper.Query<Holiday>().Result.AsQueryable();
                bool isHoliday = itemsToUpload.Any(item =>
                    holiday.Any(h => item.DateOfImport >= h.StartDate && item.DateOfImport <= h.EndDate));

                if (isHoliday)
                {
                    MessageBox.Show("当前是节假日，请稍后重试");
                    return;
                }

                // 准备一个任务列表来存储所有HTTP请求
                var tasks = new List<Task<ApiResult<string>>>();
                foreach (var item in itemsToUpload)
                {
                    var timestr = DateTime.Now;
                    var timeDifference = timestr - item.DateOfImport;
                    if (timeDifference.TotalHours < 48)
                    {
                        tasks.Add(HttpClientHelper.RequestUrl<List<BasicInformation>, ApiResult<string>>(
                            "https://localhost:44341/",
                            "api/app/fuel-synchronization/basic-informs",
                            MethodType.Post,
                            new List<BasicInformation> { item }));
                    }
                    else
                    {
                        Console.WriteLine("日期不相等: " + item.ICPRecordNumber);
                    }
                }

                // 等待所有HTTP请求完成
                var results = await Task.WhenAll(tasks);

                // 处理结果
                foreach (var res in results)
                {
                    if (res.Code == 200)
                    {
                        MessageBox.Show("批量上报成功");
                        return;
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择至少一行数据");
            }
        }


        /// <summary>
        /// 燃料类型
        /// </summary>
        /// <returns></returns>
        private async Task GetFuelType()
        {
            var FuelType = await DBHelper.Query<FuelType>();
            this.lookUpEdit1.Properties.DataSource = FuelType;
            this.lookUpEdit1.Properties.ValueMember = "FuelTypeId";
            this.lookUpEdit1.Properties.DisplayMember = "FuelTypeName";
        }

        /// <summary>
        /// 待上报查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton1_Click(object sender, EventArgs e)
        {

            string vin = textEdit1.Text;
            string str = textEdit2.Text;
            string text = textEdit3.Text;
            var selecttext = lookUpEdit1.EditValue;

            var list = DBHelper.Query<BasicInformation>();
            if (list.Result != null)
            {
                // 使用多个条件进行筛选
                var filterdata = list.Result.AsQueryable();

                // 根据ICPRecordNumber（vin）筛选
                if (!string.IsNullOrEmpty(vin))
                {
                    filterdata = filterdata.Where(b => b.ICPRecordNumber == vin);
                }

                // 根据VehicleModel（str）筛选
                if (!string.IsNullOrEmpty(str))
                {
                    filterdata = filterdata.Where(b => b.VehicleModel == str);
                }

                // 根据VersionId（text）筛选
                if (!string.IsNullOrEmpty(text) && int.TryParse(text, out int versionId))
                {
                    filterdata = filterdata.Where(b => b.VersionId == versionId);
                }

                // 根据comboBoxEdit1的选择进行筛选（如果需要的话）
                if (selecttext != null)
                {
                    filterdata = filterdata.Where(b => b.FuelTypeId == Convert.ToInt32(selecttext)); // 替换 SomeProperty 为你需要的字段
                }

                // 更新Grid数据源
                gridControl1.DataSource = filterdata.ToList();
            }
            else
            {
                // 如果没有数据，清空 gridControl
                gridControl1.DataSource = null;
            }



        }

        

        /// <summary>
        /// 上报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            await UpdateStatus();
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            pageIndex = 1;

        }

        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton5_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                GetToBeEscalated();
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton6_Click(object sender, EventArgs e)
        {
            if (pageIndex < pageCount)
            {
                pageIndex++;
                GetToBeEscalated();
            }
        }

        private async void simpleButton7_Click(object sender, EventArgs e)
        {
            await AllUpdateStatus();
        }

        public record PageGetBase(int pageIndex, int pageSize);

    }
}